import { ref, computed } from 'vue'
import { productAPI } from '@/api'
import { ElMessage } from 'element-plus'

// 商品数据状态
export const products = ref([])
export const categories = ref([])
export const stats = ref({
  total_products: 0,
  total_categories: 0,
  average_price: 0,
  total_stock: 0,
  total_sales: 0,
  top_selling: []
})

// 加载状态
export const loading = ref(false)
export const statsLoading = ref(false)

// 分页状态
export const pagination = ref({
  page: 1,
  page_size: 20,
  total: 0,
  total_pages: 0
})

// 过滤条件
export const filters = ref({
  product_name: '',
  category: '',
  min_price: null,
  max_price: null,
  min_stock: null,
  max_stock: null,
  min_sales: null,
  max_sales: null
})

// 计算属性
export const hasData = computed(() => products.value.length > 0)
export const totalRecords = computed(() => pagination.value.total)

// 获取商品数据列表
export async function fetchProducts(params = {}) {
  loading.value = true
  try {
    const queryParams = {
      page: pagination.value.page,
      page_size: pagination.value.page_size,
      ...filters.value,
      ...params
    }
    
    // 清除空值参数
    Object.keys(queryParams).forEach(key => {
      if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
        delete queryParams[key]
      }
    })
    
    const response = await productAPI.getProducts(queryParams)
    
    products.value = response.data || []
    pagination.value = {
      page: response.page || 1,
      page_size: response.page_size || 20,
      total: response.total || 0,
      total_pages: response.total_pages || 0
    }
    
    return response
  } catch (error) {
    console.error('Fetch product data error:', error)
    ElMessage.error('获取商品数据失败')
    products.value = []
    return null
  } finally {
    loading.value = false
  }
}

// 添加商品数据
export async function addProduct(data) {
  try {
    const response = await productAPI.createProduct(data)
    ElMessage.success('商品数据添加成功')
    
    // 刷新数据列表
    await fetchProducts()
    
    return response
  } catch (error) {
    console.error('Add product data error:', error)
    const errorMessage = error.response?.data?.detail || '添加商品数据失败'
    ElMessage.error(errorMessage)
    throw error
  }
}

// 删除商品数据
export async function deleteProduct(id) {
  try {
    await productAPI.deleteProduct(id)
    ElMessage.success('商品数据删除成功')
    
    // 刷新数据列表
    await fetchProducts()
    
    return true
  } catch (error) {
    console.error('Delete product data error:', error)
    const errorMessage = error.response?.data?.detail || '删除商品数据失败'
    ElMessage.error(errorMessage)
    return false
  }
}

// 更新商品数据
export async function updateProduct(id, data) {
  try {
    const response = await productAPI.updateProduct(id, data)
    ElMessage.success('商品数据更新成功')
    
    // 刷新数据列表
    await fetchProducts()
    
    return response
  } catch (error) {
    console.error('Update product data error:', error)
    const errorMessage = error.response?.data?.detail || '更新商品数据失败'
    ElMessage.error(errorMessage)
    throw error
  }
}

// 获取商品类别列表
export async function fetchCategories() {
  try {
    const response = await productAPI.getCategories()
    categories.value = response || []
    return response
  } catch (error) {
    console.error('Fetch categories error:', error)
    ElMessage.error('获取商品类别列表失败')
    categories.value = []
    return []
  }
}

// 获取统计信息
export async function fetchStats() {
  statsLoading.value = true
  try {
    const response = await productAPI.getStats()
    
    // 添加图表数据
    const enhancedStats = {
      ...response,
      // 商品类别分布数据
      category_distribution: await getCategoryDistribution(),
      // 商品价格分布数据
      price_distribution: await getPriceDistribution()
    }
    
    stats.value = enhancedStats || {
      total_products: 0,
      total_categories: 0,
      average_price: 0,
      total_stock: 0,
      total_sales: 0,
      top_selling: [],
      category_distribution: [],
      price_distribution: []
    }
    return enhancedStats
  } catch (error) {
    console.error('Fetch stats error:', error)
    ElMessage.error('获取统计信息失败')
    stats.value = {
      total_products: 0,
      total_categories: 0,
      average_price: 0,
      total_stock: 0,
      total_sales: 0,
      top_selling: [],
      category_distribution: [],
      price_distribution: []
    }
    return null
  } finally {
    statsLoading.value = false
  }
}

// 获取商品类别分布
async function getCategoryDistribution() {
  try {
    const response = await productAPI.getCategoryStats()
    return response || []
  } catch (error) {
    console.error('Get category distribution error:', error)
    return []
  }
}

// 获取价格分布
async function getPriceDistribution() {
  try {
    const response = await productAPI.getPriceStats()
    return response || []
  } catch (error) {
    console.error('Get price distribution error:', error)
    return []
  }
}

// 设置过滤条件
export function setFilters(newFilters) {
  filters.value = { ...filters.value, ...newFilters }
  pagination.value.page = 1 // 重置页码
}

// 清除过滤条件
export function clearFilters() {
  filters.value = {
    product_name: '',
    category: '',
    min_price: null,
    max_price: null,
    min_stock: null,
    max_stock: null,
    min_sales: null,
    max_sales: null
  }
  pagination.value.page = 1
}

// 设置分页
export function setPagination(page, pageSize = null) {
  pagination.value.page = page
  if (pageSize) {
    pagination.value.page_size = pageSize
  }
}

// 获取热门商品
export function getTopSelling(limit = 5) {
  return stats.value.top_selling.slice(0, limit)
}

// 初始化数据
export async function initProductData() {
  await Promise.all([
    fetchProducts(),
    fetchCategories(),
    fetchStats()
  ])
}